package com.grape.bosfore.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.core.MediaType;

import org.apache.commons.io.FileUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.grape.bosfore.action.common.BaseAction;
import com.grape.domain.base.PageBean;
import com.grape.domain.take_delivery.Promotion;

import freemarker.template.Configuration;
import freemarker.template.Template;

@Controller
@Namespace("/promotion")
@Scope("prototype")
@ParentPackage("json-default")
@SuppressWarnings("all")
public class PromotionAction extends BaseAction<Promotion>{
	private static final long serialVersionUID = 1L;

	@Action(value="pageQuery" ,results=@Result(name="success",type="json"))
	public String pageQuery() {
		PageBean<Promotion> pageBean = WebClient.create("http://localhost:8080/bos_management/faraway/promotionService/pageQuery")
				.replaceQueryParam("page", page)
				.replaceQueryParam("rows", rows)
				.accept(MediaType.APPLICATION_XML)
				.get(PageBean.class);
			
		ServletActionContext.getContext().getValueStack().push(pageBean);
		
		return SUCCESS;
	}
	
	@Action(value="detail")
	public String detail() throws Exception {
		// 尝试获取页面需要的促销详情
		String realPath = ServletActionContext.getServletContext().getRealPath("freemaker");
		File htmlFile = new File(realPath+"/"+model.getId()+".html");
		
		// 不存在自己造一个
		if (!htmlFile.exists()) {
			// 初始化配置模板位置
			Configuration configuration = new Configuration(Configuration.VERSION_2_3_0);
			configuration.setDirectoryForTemplateLoading(new File("src/main/webapp/WEB-INF/template"));
			// 获取模板
			Template template = configuration.getTemplate("promotion_detail.ftl");
			
			// 获取需要的数据
			Promotion promotion = WebClient.create("http://localhost:8080/bos_management/faraway/promotionService/findOne")
					.replaceQueryParam("id", model.getId())
					.accept(MediaType.APPLICATION_XML)
					.get(Promotion.class);
			
			// 要存入的数据
			Map<String,Object> mp = new HashMap<>();
			mp.put("promotion", promotion);
			
			// 合并输出到促销详情集
			template.process(mp, new OutputStreamWriter(new FileOutputStream(htmlFile)));
		}
		
		// 返回
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		FileUtils.copyFile(htmlFile, ServletActionContext.getResponse().getOutputStream());
		
		return NONE;
	}
	
}
